from google.appengine.ext import db
from google.appengine.api import memcache
from domain import topic
from repository import baserepository

class TopicRepository(baserepository.BaseRepository):

    def _fetchCurrent(self, howmany):
        query = db.GqlQuery("SELECT * FROM Topic WHERE enabled=True ORDER BY updatedate DESC")
        topics = query.fetch(howmany)
        return topics

    def getCurrent(self, howmany):
        cachedcurrenttopics = memcache.get('currenttopics')
        if (cachedcurrenttopics is not None):
            return cachedcurrenttopics
        else:
            return self._fetchCurrent(howmany)

    def getByArticle(self, article):
        topics = db.GqlQuery("SELECT * FROM Topic WHERE enabled=True AND article = :1 ORDER BY updatedate DESC", article)
        return topics

    def getByDocument(self, document):
        topics = db.GqlQuery("SELECT * FROM Topic WHERE enabled=True AND document = :1 ORDER BY updatedate DESC", document)
        return topics

    def getByDiscussion(self, discussion):
        topics = db.GqlQuery("SELECT * FROM Topic WHERE enabled=True AND discussion = :1 ORDER BY updatedate DESC", discussion)
        return topics

    def save(self, newtopic):
        return super(TopicRepository, self).save(newtopic, topic.Topic)

    def delete(self, oldtopic):
        super(TopicRepository, self).delete(oldtopic, topic.Topic)

    def getByKey(self, topickey):
        return super(TopicRepository, self).getByKey(topickey, topic.Topic)